//#ifdef APP-PLUS
const BluetoothAdapter = plus.android.importClass(
  "android.bluetooth.BluetoothAdapter"
);
const Intent = plus.android.importClass("android.content.Intent");
const IntentFilter = plus.android.importClass("android.content.IntentFilter");
const BluetoothDevice = plus.android.importClass(
  "android.bluetooth.BluetoothDevice"
);
const UUID = plus.android.importClass("java.util.UUID");
const Toast = plus.android.importClass("android.widget.Toast");
//连接串口设备的 UUID
const MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

const invoke = plus.android.invoke;
const bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 本机蓝牙适配器
const activity = plus.android.runtimeMainActivity();

let btSocket = null;
let btInStream = null;
let btOutStream = null;
let setIntervalId = 0;

let receiver; // 蓝牙搜索广播接收器
let btStatusReceiver;
//#endif

let ready = false;
let isStop = false;

export function startDiscovery(fn) {
  console.log("开始搜索");

  cancelDiscovery();

  if (!ready) {
    console.log("ready");
    ready = true;
    uni.startBluetoothDevicesDiscovery();
    setTimeout(() => {
      uni.stopBluetoothDevicesDiscovery();
    }, 2000);
  }

  bluetoothAdapter.startDiscovery(); // 开启搜索
  receiver = plus.android.implements(
    "io.dcloud.android.content.BroadcastReceiver",
    {
      onReceive: function (context, intent) {
        console.log("onReceive");
        plus.android.importClass(intent);
        const bleDevice = intent.getParcelableExtra(
          BluetoothDevice.EXTRA_DEVICE
        );
        // 未配对
        // const state = bleDevice.getBondState();// 10
        // 配对 BleDevice.createBond()
        if (
          intent.getAction() ==
          "android.bluetooth.adapter.action.DISCOVERY_FINISHED"
        ) {
          console.log("搜索结束");
          if (!isStop) startDiscovery(fn);
          return;
        }
        const device = {
          name: bleDevice.getName(),
          mac: bleDevice.getAddress(),
          deviceId: bleDevice.getAddress(), // 保持和BLE蓝牙字段一致
        };
        if (fn) fn(device);
      },
    }
  );
  const filter = new IntentFilter();
  const bdevice = new BluetoothDevice();
  filter.addAction(bdevice.ACTION_FOUND);
  filter.addAction(bluetoothAdapter.ACTION_DISCOVERY_STARTED);
  filter.addAction(bluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  filter.addAction(bluetoothAdapter.ACTION_STATE_CHANGED);
  activity.registerReceiver(receiver, filter); //注册监听
}

function cancelDiscovery() {
  if (bluetoothAdapter.isDiscovering()) {
    bluetoothAdapter.cancelDiscovery();
  }

  if (receiver) {
    activity.unregisterReceiver(receiver); // 取消监听
    receiver = null;
  }
}

export function stopDiscovery(_isStop = true) {
  isStop = true;
  cancelDiscovery();
}

export function connect(address) {
  if (!address) throw "缺少设备MAC";

  closeBtSocket();

  try {
    let device = invoke(bluetoothAdapter, "getRemoteDevice", address);
    btSocket = invoke(device, "createRfcommSocketToServiceRecord", MY_UUID);
  } catch (e) {
    console.error("[native-bluetooth] 连接失败，获取Socket失败！", e);
    throw e;
  }

  try {
    invoke(btSocket, "connect");

    btInStream = invoke(btSocket, "getInputStream");
    btOutStream = invoke(btSocket, "getOutputStream");
  } catch (e) {
    console.error("[native-bluetooth] 创建输入输出流失败！", e);
    closeBtSocket();
    throw e;
  }

  console.log("[native-bluetooth] 连接成功");

  read(address);
}

function _init() {
  console.log("[native-bluetooth] init");
  if (btStatusReceiver != null) {
    try {
      activity.unregisterReceiver(btStatusReceiver);
    } catch (e) {
      console.error(e);
    }
    btStatusReceiver = null;
  }
  btStatusReceiver = plus.android.implements(
    "io.dcloud.android.content.BroadcastReceiver",
    {
      onReceive: (context, intent) => {
        plus.android.importClass(context);
        plus.android.importClass(intent);

        const action = intent.getAction();

        if (action == BluetoothAdapter.ACTION_ACL_DISCONNECTED) {
          // 蓝牙设备断开连接
          const device = intent.getParcelableExtra(
            BluetoothDevice.EXTRA_DEVICE
          );
          console.log("[native-bluetooth] 设备断开" + device.getName());
        } else if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
          const state = intent.getIntExtra(
            BluetoothAdapter.EXTRA_STATE,
            BluetoothAdapter.ERROR
          );
          if (state == BluetoothAdapter.STATE_OFF) {
            console.log("[native-bluetooth] 蓝牙已关闭");
          }
        }

        // switch (action) {
        //   case BluetoothAdapter.ACTION_STATE_CHANGED:
        //     let blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0);
        //     let stateStr = "";

        //     console.log("blueState");

        //     switch (blueState) {
        //       case BluetoothAdapter.STATE_TURNING_ON:
        //         stateStr = "STATE_TURNING_ON";
        //         break;
        //       case BluetoothAdapter.STATE_ON:
        //         stateStr = "STATE_ON";
        //         break;
        //       case BluetoothAdapter.STATE_TURNING_OFF:
        //         stateStr = "STATE_TURNING_OFF";
        //         break;
        //       case BluetoothAdapter.STATE_OFF:
        //         stateStr = "STATE_OFF";
        //         break;
        //     }
        //     break;
        // }
      },
    }
  );

  let filter = new IntentFilter();
  filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

  activity.registerReceiver(btStatusReceiver, filter);
}

function read(address) {
  console.log("[native-bluetooth] 读取蓝牙数据");

  let setTimeCount = 0;
  let dataBuffer = []; // 全局缓冲区，存储接收到的数据

  clearInterval(setIntervalId);
  setIntervalId = setInterval(() => {
    setTimeCount++;

    let t = new Date().getTime();
    //心跳检测
    if (setTimeCount % 20 == 0) {
      try {
        btOutStream.write([0b00]);
      } catch (e) {
        console.log("[native-bluetooth] 蓝牙中断");
        // this.state.readThreadState = false;
        // this.options.connExceptionCallback && this.options.connExceptionCallback(e);
      }
    }
    let dataArr = [];
    while (invoke(btInStream, "available") !== 0) {
      let data = invoke(btInStream, "read");
      dataArr.push(data);
      let ct = new Date().getTime();
      if (ct - t > 20) {
        break;
      }
    }

    if (dataArr.length > 0) {
      dataBuffer = dataBuffer.concat(dataArr);

      // 检查缓冲区中是否有 `\r\n`（即 [13, 10]）
      const crlfIndex = findCrLfIndex(dataBuffer);

      if (crlfIndex !== -1) {
        // 提取 \r\n 之前的所有数据（完整的一行）
        const completeData = dataBuffer.slice(0, crlfIndex);
        // console.log('[native-bluetooth] completeData', toAscii(completeData))

        uni.$emit("native_bluetooth_data", {
          address,
          data,
        });

        // 剩余数据留在缓冲区（\r\n 之后的数据）
        dataBuffer = dataBuffer.slice(crlfIndex + 2); // +2 跳过 \r\n
      }
    }
  }, 40);
}

function closeBtSocket() {
  clearInterval(setIntervalId);

  if (btSocket) {
    try {
      btSocket.close();
      btSocket = null;
    } catch (e) {
      console.error(e);
    }
  }
}

// 辅助函数：查找 \r\n 的位置
function findCrLfIndex(buffer) {
  for (let i = 0; i < buffer.length - 1; i++) {
    if (buffer[i] === 13 && buffer[i + 1] === 10) {
      // 13=\r, 10=\n
      return i;
    }
  }
  return -1; // 未找到
}

function toAscii(buff) {
  const asciiChars = buff.map((num) => String.fromCharCode(num));
  return asciiChars;
}

_init();

function disconnect() {
  closeBtSocket();
}
